package com.health.work.activity;


import java.util.List;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.Overlay;
import com.health.work.R;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;

import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


public class MyLocActivity extends MapActivity {
    private MapController mapController;
    private MapView mapView;
	private BMapManager mBMapMan;
	private MKLocationManager mLocationManager;
    private double userLatitude;
	private double userLongitude;
	private MyLocationOverlay myLocationOverlay;
	private MyOverLay myOverLay;
	
	private double mLatitude=39.95;//经纬度
	private double mLongitude=116.37;//经纬度
	private GeoPoint geoCenter;
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myloc);
       
        //zhai add baidu maps
        if(getIntent()!=null){
        	if(getIntent().getDoubleExtra("Latitude", 0)!=0
        			&& getIntent().getDoubleExtra("Longitude", 0)!=0){
        		mLatitude=getIntent().getDoubleExtra("Latitude", 0);
        		mLongitude=getIntent().getDoubleExtra("Longitude", 0);
        	}
        }
        mBMapMan = new BMapManager(getApplication());
        mBMapMan.init("C208CA8EB946C36C999C71738484305E850EE7B4", new MKGeneralListener() {
        	// key值不正确
        	@Override
        	public void onGetPermissionState(int arg0) {
        	if (arg0 == 300) {
        	Toast.makeText(MyLocActivity.this,"密钥错误",
        	Toast.LENGTH_LONG).show();
        	}
        	}
        	//网络出错
        	@Override
        	public void onGetNetworkState(int arg0) {
        	Toast.makeText(MyLocActivity.this,"网络错误",
        	Toast.LENGTH_LONG).show();
        	}
        	});
        
        super.initMapActivity(mBMapMan);
         
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);  //设置启用内置的缩放控件
         
		// 设置初始地图的中心位置
//		geoCenter = new GeoPoint((int) (39.95 * 1000000),
//				(int) (116.37 * 1000000));
		mapController = mapView.getController();
//		mapController.setCenter(geoCenter);

//		mLocationManager = mBMapMan.getLocationManager();
//		// 通过enableProvider和disableProvider方法，选择定位的Provider
//		mLocationManager.enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
//		mLocationManager.enableProvider(MKLocationManager.MK_GPS_PROVIDER);
//		// 返回手机位置
//		mLocationManager.requestLocationUpdates(locationListener);
//		mLocationManager.setNotifyInternal(5, 2);
//		// 添加定位图层
//		myLocationOverlay = new MyLocationOverlay(this, mapView);
//		myLocationOverlay.enableMyLocation(); // 启用定位
//		myLocationOverlay.enableCompass(); // 启用指南针
//		mapView.getOverlays().add(myLocationOverlay);
		mapView.setTraffic(true);// 交通地图
		// mapView.setSatellite(true);// 卫星地图
		mapController.setZoom(12);// 设置缩放级别
		mapView.invalidate();// 刷新地图
        //zhai ended baidu maps
        
//        LocationManager locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
//        mapView=(MapView) this.findViewById(R.id.mapview);
//        //设置交通模式
//        mapView.setTraffic(true);
//        //设置卫星模式
//        mapView.setSatellite(false);
//        //设置街景模式
//        mapView.setStreetView(false);
//        //设置缩放控制
//        mapView.setBuiltInZoomControls(true);
//        mapView.setClickable(true);
//        mapView.setEnabled(true);
//        //得到MapController实例 
//        mapController=mapView.getController();
//        mapController.setZoom(15);
//        
//        myOverLay=new MyOverLay(MyLocActivity.this);
//        List<Overlay> overLays=mapView.getOverlays();
//        overLays.add(myOverLay);
//        
//        Criteria criteria=new Criteria();
//        criteria.setAccuracy(Criteria.ACCURACY_FINE);
//        criteria.setAltitudeRequired(false);
//        criteria.setBearingRequired(false);
//        criteria.setCostAllowed(false);
//        criteria.setPowerRequirement(Criteria.POWER_LOW);
//        //取得效果最好的Criteria
//        String provider=locationManager.getBestProvider(criteria, true);
//        //得到Location
//        Location location=locationManager.getLastKnownLocation(provider);
//        updateWithLocation(location);
//        //注册一个周期性的更新，3秒一次
//        locationManager.requestLocationUpdates(provider, 3000, 0, locationListener);
       
//        mapController.animateTo(this.getCurrentGeoPoint());// 通过动画方式移动到指定坐标  
		setProductLocation(mLatitude, mLongitude);
    }
    
    //根据经纬度 在地图上显示位置  zhailong
    public void setProductLocation(double latitude ,double longitude){
    	Log.i("zhailong", latitude+"~~~~~~~~~~~"+longitude);
      myOverLay=new MyOverLay(MyLocActivity.this);
      myOverLay.setLocation(latitude,longitude);
      mapView.getOverlays().add(myOverLay);
      Log.i("zhailong", "~~~~~~~~~~~");
      geoCenter = new GeoPoint((int) (latitude * 1000000),
				(int) (longitude * 1000000));
      mapController.setCenter(geoCenter);
    }
    
  //获取经度纬度
    private LocationListener locationListener = new LocationListener() {  
	@Override
    public void onLocationChanged(Location location) {
    if (location != null) {  
    userLatitude = location.getLatitude() * 1E6;  
                    userLongitude = location.getLongitude() * 1E6;
                    GeoPoint mypoint = new GeoPoint((int)(userLatitude), (int)(userLongitude));
                    mapView.getController().animateTo(mypoint);  
                }
    }
    };
    
//    private GeoPoint getCurrentGeoPoint() { 
//        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
//        Location location = locationManager 
//                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
//        return new GeoPoint((int) (location.getLatitude() * 1e6), 
//                (int) (location.getLongitude() * 1e6)); 
//    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        menu.add(0, 1, 1, getString(R.string.location_traffic));
        menu.add(0,2,2,getString(R.string.location_weixing));
        menu.add(0,3,3,getString(R.string.location_street));
        
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
         super.onOptionsItemSelected(item);
         switch (item.getItemId()) {
        case 1://交通模式
            mapView.setTraffic(true);
            mapView.setSatellite(false);
            mapView.setStreetView(false);
            break;
        case 2://卫星模式
            mapView.setSatellite(true);
            mapView.setStreetView(false);
            mapView.setTraffic(false);
            break;
        case 3://街景模式
            mapView.setStreetView(true);
            mapView.setTraffic(false);
            mapView.setSatellite(false);
            break;
        default:
            mapView.setTraffic(true);
            mapView.setSatellite(false);
            mapView.setStreetView(false);
            break;
        }
        return true;
    }
//    private void updateWithLocation(Location location){
//        if(location!=null){
//            //为绘制类设置坐标
//            myOverLay.setLocation(location);
//            GeoPoint geoPoint=new GeoPoint((int)(location.getLatitude()*1E6), (int)(location.getLongitude()*1E6));
//            //定位到指定的坐标
//            mapController.animateTo(geoPoint);
//            mapController.setZoom(15);
//        }else {
//            myOverLay.setLocation(location);
//            GeoPoint geoPoint=geoPoint = AssistUtils.getGeoPoint(this);
//            //定位到指定的坐标
//            mapController.animateTo(geoPoint);
//            mapController.setZoom(15);
//        }
//    }
//    private final LocationListener locationListener=new LocationListener() {
//        
//        @Override
//        public void onStatusChanged(String provider, int status, Bundle extras) {
//            
//        }
//        
//        @Override
//        public void onProviderEnabled(String provider) {
//            
//        }
//        
//        @Override
//        public void onProviderDisabled(String provider) {
//            
//        }
//        //当坐标改变时出发此函数
//        @Override
//        public void onLocationChanged(Location location) {
//            updateWithLocation(location);
//    };
    class MyOverLay extends Overlay{
        
        private Location location;
        private Context mConext;
        private double mLatitude;
        private double mLongitude;
        public MyOverLay(Context context)
        {
            this.mConext=context;
        }
//        public void setLocation(Location location){
//            this.location=location;
//        }
        
        public void setLocation(double latitude ,double longitude){
        	mLatitude=latitude;
        	mLongitude=longitude;
        }
        
        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
                long when) {
            // TODO Auto-generated method stub
            super.draw(canvas, mapView, shadow);
            Paint paint=new Paint();
            Point myScreen=new Point();
            //将经纬度换成实际屏幕的坐标。
            GeoPoint geoPoint;
//            if(location!=null) {
//                geoPoint=new GeoPoint((int)(location.getLatitude()*1E6), (int)(location.getLongitude()*1E6));
//            } else {
//                geoPoint = AssistUtils.getGeoPoint(mConext);
//            }
            Log.i("be...", "draw");
            geoPoint=new GeoPoint((int)(mLatitude*1E6), (int)(mLongitude*1E6));
            mapView.getProjection().toPixels(geoPoint, myScreen);
            paint.setStrokeWidth(1);
            
            paint.setARGB(255, 255, 0, 0);
            paint.setStyle(Paint.Style.STROKE);
            Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.icon);
            canvas.drawBitmap(bmp, myScreen.x, myScreen.y,paint);
            canvas.drawText("", myScreen.x, myScreen.y, paint);
            super.draw(canvas, mapView, shadow);
            return true;
            
        }
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(getString(R.string.location_quite))
                    .setCancelable(false)
                    .setPositiveButton(getString(R.string.ad_makesure),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    MyLocActivity.this.finish();
                                    android.os.Process
                                            .killProcess(android.os.Process
                                                    .myPid());
                                      android.os.Process.killProcess(android.os.Process.myTid());
                                      android.os.Process.killProcess(android.os.Process.myUid());
                                }
                            })
                    .setNegativeButton(getString(R.string.back),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.cancel();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
    
    @Override
    protected void onDestroy() {
        if (mBMapMan != null) {
            mBMapMan.destroy();
            mBMapMan = null;
        }
        super.onDestroy();
    }
    @Override
    protected void onPause() {
        if (mBMapMan != null) {
//        	mLocationManager.removeUpdates(locationListener);
            mBMapMan.stop();
        }
        super.onPause();
    }
    @Override
    protected void onResume() {
        if (mBMapMan != null) {
        	 // 获取位置管理者，视图根据位置监听更新位置  
//        	mLocationManager.requestLocationUpdates(locationListener);  
            //打开定位图标  
//            myLocationOverlay.enableMyLocation();  
            mBMapMan.start();
        }
        super.onResume();
    }

}